package main

import (
	"database/sql"
	"net/http"
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/wtf/mahjong/model"
	"github.com/wtf/mahjong/utils"
)

func levelPeople(write http.ResponseWriter, request *http.Request) {
	key := utils.Config.PkgName + "_rank"

	// 从池里获取连接
	rc := model.RedisClient.Get()
	// 用完后将连接放回连接池
	defer rc.Close()

	newList := make(map[int]int)

	list, resErr := redis.Strings(rc.Do("ZRANGE", key, 0, -1, "WITHSCORES"))
	utils.CheckErr(write, resErr, 101, "levelPeople:获取list数量失败")
	if resErr != nil {
		return
	}

	for x := 0; x < len(list); x += 2 {
		level, _ := strconv.Atoi(list[x+1])
		newList[level] += 1
	}

	returnDa := utils.ReturnData{
		Errcode: 0,
		Errmsg:  "is ok",
		Data:    newList,
	}
	returnDa.Returnfunc(write)
}

func test(write http.ResponseWriter, request *http.Request) {
	utils.Info("test check")

	key := utils.Config.PkgName + "_rank"
	// 从池里获取连接
	rc := model.RedisClient.Get()
	// 用完后将连接放回连接池
	defer rc.Close()

	newList := make(map[string]int)
	var rows *sql.Rows
	var err error
	rows, err = model.Db.Query("select unique_id from users where channel = ? and time between ? and ?", "chance_mp09", 1548604800, 1548691199)
	utils.CheckErr(write, err, 101, "test:失败1")
	if err != nil {
		return
	}

	newList["0"] = 0
	newList["1-3"] = 0
	newList["4-6"] = 0
	newList["7-10"] = 0
	newList["11-15"] = 0
	newList["16-20"] = 0
	newList["21-30"] = 0
	newList["31-40"] = 0
	newList["41-50"] = 0
	newList["51-"] = 0
	for rows.Next() {
		openId := ""
		err = rows.Scan(&openId)
		utils.CheckErr(write, err, 102, "test:失败2")
		if err != nil {
			return
		}
		score, err := redis.Int(rc.Do("zscore", key, openId))
		utils.CheckErr(write, err, 103, "test:失败3")
		if err != nil {
			return
		}

		if score == 0 {
			newList["0"] += 1
		} else if score >= 1 && score <= 3 {
			newList["1-3"] += 1
		} else if score >= 4 && score <= 6 {
			newList["4-6"] += 1
		} else if score >= 7 && score <= 10 {
			newList["7-10"] += 1
		} else if score >= 11 && score <= 15 {
			newList["11-15"] += 1
		} else if score >= 16 && score <= 20 {
			newList["16-20"] += 1
		} else if score >= 21 && score <= 30 {
			newList["21-30"] += 1
		} else if score >= 31 && score <= 40 {
			newList["31-40"] += 1
		} else if score >= 41 && score <= 50 {
			newList["41-50"] += 1
		} else if score >= 51 {
			newList["51-"] += 1
		}
	}

	returnDa := utils.ReturnData{
		Errcode: 0,
		Errmsg:  "is ok",
		Data:    newList,
	}
	returnDa.Returnfunc(write)
}

func createScene1(openId string) (id int, err error) {
	scene := model.Scene{
		OpenId:    openId,
		Time:      int(time.Now().Unix()),
		TableName: "scene_1",
	}

	id, err0 := scene.Create()
	if err0 != nil {
		return 0, err0
	}

	return id, nil

}
